<?php
/**
 * Created by PhpStorm.
 * 售后工单
 * User: ciacm
 * Date: 2017/5/19
 * Time: 13:55
 */

namespace SDXApi\Service;


use SDXApi\Model\WorkorderContentModel;
use SDXApi\Model\WorkorderModel;

class WorkorderService {

    //用户id
    public $uid ;

    //生鲜售后期限时间(24小时)
    protected $fresh_time = 86400;

    //生鲜售后期限时间（7天）
    protected $other_time = 604800;

    //生鲜分类
    protected $fresh_cat = array(154,700,192,703,461);

    /*
     * 获取工单申请记录列表
     * Created By caicm
     * @param string $keyword 关键词（商品名称、订单号）模糊搜索
     * @param int $limit 分页
     * @return mixed
     */
    public function get_workorder_apply_record($keyword='', $limit=10){

        $workorder_list = D('Workorder')->get_workorder_apply_record($this->uid, $keyword, $limit);

        foreach ($workorder_list as $key=>$value){

            $workorder_list[$key]['add_date'] = local_date('Y-m-d H:i', $value['add_time']);
            $workorder_list[$key]['add_time'] = localtotime($value['add_time']);

        }

        return $workorder_list;

    }

    /*
     * 获取工单订单列表
     * Created By caicm
     * @param string $keyword 关键词（商品名称、订单号）模糊搜索
     * @param int $limit 分页
     * @return mixed
     */
    public function get_order_list($keyword='', $limit=10){

        $order_list = D('Workorder')->get_order_list($this->uid, $keyword, $limit);

        //循环获取商品
        foreach ($order_list as $key=>$value){

            $type = $this->check_order_overtime($value['order_id']);

            $goods = $this->dispose_goods($value['order_id'], $value['confirm_time'], 1, '', $type);

            $order_list[$key]['order_date'] = local_date('Y-m-d H:i', $value['add_time']);
            $order_list[$key]['order_time'] = localtotime($value['add_time']);
            $order_list[$key]['goods_list'] = $goods['goods_list'];
            $order_list[$key]['order_workorder_type'] = $type ? $type : $goods['order_workorder_type'];

            unset($order_list[$key]['add_time']);
            unset($order_list[$key]['confirm_time']);

        }

        return $order_list;

    }

    /**
     * 查询是否有已处理的超时免单
     * @param $order_id
     * @return int
     */
    protected function check_order_overtime($order_id){
        $where = array(
            'order_id' => $order_id,
            'state' => 2
        );

        $overtime = M('order_info_overtime')->where($where)->count();
        return $overtime ? 4 : 0;
    }

    /*
     * 处理商品数据
     * Created By caicm
     * @param int $order_id 订单id
     * $param int $confirm_time 确认收货时间
     * @return mixed
     */
    public function get_goodslist_by_orderid($order_id=0, $confirm_time=0, $limit=''){

        $type = $this->check_order_overtime($order_id);

        return $this->dispose_goods($order_id, $confirm_time, 0, $limit, $type);
    }

    /*
     * 处理商品数据
     * Created By caicm
     * @param int $order_id 订单id
     * $param int $confirm_time 确认收货时间
     * @return mixed
     */
    protected function dispose_goods($order_id=0, $confirm_time=0, $is_order_list=0, $limit='', $type=0){
        $in_overtime = 0;   //超过售后期限
        $in_time = 0;       //在售后期限
        $in_workorder = 0;  //已申请售后

        //获取工单订单商品列表
        $goods_list = D('Workorder')->get_order_goods($order_id, $limit);

        //商品处理
        foreach ($goods_list as $key=>$value){
            $is_deadline = 0;
            $workorder_info = array();

            //查询商品是否存在售后记录（排查取消状态）
            $workorder_info = D('Workorder')->get_workorder_info($this->uid, $order_id, $value['goods_id']);
            $goods_list[$key]['workorder_id'] = $workorder_info['id'] ? $workorder_info['id'] : 0;

            //是否在售后期限 1：是 ， 0：否
            $is_deadline = $this->get_category_deadline($value['cat_id'], $confirm_time);

            //工单类型 0：超过售后期限，1：在售后期限（可申请工单），2：已申请售后（查看详情）
            $goods_list[$key]['workorder_type'] = $workorder_info ? 2 : $is_deadline;

            if($workorder_info){
                $in_workorder = 1;
            }else{

                //订单商品是否已退款
                if($this->check_refund($order_id, $value['goods_id'], $value['goods_number'])){
                    //商品已退款
                    $goods_list[$key]['workorder_type'] = 3;
                }

                if($is_deadline)
                    $in_time = 1;
                else
                    $in_overtime = 1;
            }
            unset($goods_list[$key]['cat_id']);

            if($type){
                $goods_list[$key]['workorder_type'] = $type;
            }

        }

        if($is_order_list == 0){
            return $goods_list;
        }

        $data = array(
            'goods_list' => $goods_list,
            'order_workorder_type' => $this->get_order_workorder_type($in_workorder, $in_time, $in_overtime)
        );

        return $data;

    }

    /**
     * 检查订单商品是否已退款
     * @param int $order_id
     * @param int $goods_id
     * @param int $goods_num
     * @return int
     */
    public function check_refund($order_id=0, $goods_id=0, $goods_num=0){
        $refund_num = D('Workorder')->get_goods_refund_num($order_id, $goods_id);
        if($refund_num >= $goods_num){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 取消工单
     * Created By caicm
     * @param int $workorder_id
     * @return bool
     */
    public function cancel_workorder($workorder_id=0){
        $workorder_modell = D('Workorder');

        //开启事务处理
        $workorder_modell->startTrans();

        //取消工单
        $workorder_status = $workorder_modell->cancel_workorder($workorder_id);
        //写入工单内容表
        $workorder_content_id = D('WorkorderContent')->add_workorder_content($workorder_id, '取消申请', 4);

        if($workorder_status && $workorder_content_id){
            $workorder_modell->commit();
            return ture;
        }else{
            //回滚
            $workorder_modell->rollback();
            return false;
        }
    }

    /*
     * 添加工单
     * Created By caicm
     * @param int $uid 用户id
     * @param int $order_id 订单id
     * @param string $order_sn 订单号
     * @param int $goods_id 商品id
     * @param string $goods_name 商品名称
     * @param int $cause 原因
     * @param int $dispose_way 处理方式
     * @param string $content 内容
     * @param string $id_list 图片id集
     * @return mixed
     */
    public function add_workorder($uid=0, $order_id=0, $order_sn='', $goods_id=0, $goods_name='', $cause=0, $dispose_way=0, $content='', $id_list=''){

        $workorder_modell = D('Workorder');

        //获取用户名称
        $user_name = M('users')->where(array('user_id'=>$uid))->getField('user_name');

        //开启事务处理
        $workorder_modell->startTrans();

        //写入工单表
        $workorder_id = $workorder_modell->add_workorder($uid, $user_name, $order_id, $order_sn, $goods_id, $goods_name, $cause, $dispose_way);
        //写入工单内容表
        $workorder_content_id = D('WorkorderContent')->add_workorder_content($workorder_id, $content);

        $update_workorder_img = 1;
        //绑定工单图片
        if($id_list) {
            $update_workorder_img = D('WorkorderContent')->update_workorder_img($id_list, $workorder_content_id);
        }

        if($workorder_id && $workorder_content_id && $update_workorder_img){
            $workorder_modell->commit();
            return $workorder_id;
        }else{
            //回滚
            $workorder_modell->rollback();
            return false;
        }

    }

    /*
     * 追加工单描述
     * Created By caicm
     * @param int $workorder_id 工单id
     * @param string $content 内容
     * @param string $id_list 图片id集
     * @return mixed
     */
    public function again_add_workorder( $workorder_id=0, $content='', $id_list=''){

        $workorder_modell = D('Workorder');

        //开启事务处理
        $workorder_modell->startTrans();

        //修改工单表追加描述
        $update_workorder = $workorder_modell->update_workorder_overlay($workorder_id);

        //写入工单内容表
        $workorder_content_id = D('WorkorderContent')->add_workorder_content($workorder_id, $content);

        $update_workorder_img = 1;

        //绑定工单图片
        if($id_list){
            $update_workorder_img = D('WorkorderContent')->update_workorder_img($id_list, $workorder_content_id);
        }

        if($update_workorder && $workorder_content_id && $update_workorder_img){
            $workorder_modell->commit();
            return ture;
        }else{
            //回滚
            $workorder_modell->rollback();
            return false;
        }

    }

    /**
     * 获取工单问题描述
     * Created By caicm
     * @param int $workorder_id
     * @return mixed
     */
    public function get_content_list($workorder_id=0){
        $workorder_content = new WorkorderContentModel();
        $content_list = $workorder_content->get_content_list($workorder_id);
        //循环获取问题描述图片
        foreach ($content_list as $key=>$value){
            $content_list[$key]['add_date'] = local_date('Y-m-d H:i', $value['add_time']);
            $content_list[$key]['add_time'] = localtotime($value['add_time']);
            $content_list[$key]['title'] = $value['role']==1?'问题描述':'审核留言';
            $content_list[$key]['img'] = $workorder_content->get_content_img($value['id']);
        }
        return $content_list;
    }

    /**
     * 自动关闭工单处理
     * Created By caicm
     * @param int $close_day
     * @return array
     */
    public function close_workorder($close_day=7){
        $is_ture = array();
        $is_false = array();
        $workorder = new WorkorderModel();

        $workorder_list = $workorder->get_close_workorder($close_day);
        if(!$workorder_list){
            return 0;
        }

        foreach($workorder_list as $key=>$val){
            $workorder_modell = D('Workorder');
            //开启事务处理
            $workorder_modell->startTrans();

            //处理关闭工单
            $close_workorder = $workorder_modell->cancel_workorder($val[id], 5);

            //写入工单内容表
            $workorder_content_id = D('WorkorderContent')->add_workorder_content($val[id], '关闭工单', 5, '系统操作', 3);

            if($close_workorder && $workorder_content_id){
                $workorder_modell->commit();
                $is_ture[] = $val[id];
            }else{
                //回滚
                $workorder_modell->rollback();
                $is_false[] = $val[id];
                continue;
            }
        }

        return array(
            'is_ture' => count($is_ture),
            'is_false' => count($is_false)
        );

    }

    /**
     * 进度内容列表
     * Created By caicm
     * @param int $workorder_id
     * @return array
     */
    public function get_paln_list($workorder_id=0){
        $paln_list = array();
        $workorder_content_modell = new WorkorderContentModel();
        $content_list = $workorder_content_modell->get_content_list($workorder_id);
        foreach ($content_list as $key=>$value){
            $title = '';
            if($key == 0){
                $content = '审核已提交，等待客服受理，我们将在1-3个工作日内为您尽快处理';
            }else{

                switch ($value['status']){
                    case 1:
                        $content = '补充描述，等待客服受理，我们将在1-3个工作日内为您尽快处理';
                        break;
                    case 2:
                        $content = $value['content'];
                        break;
                    case 3:
                        $title = '申请被拒绝';
                        $content = $value['content'];
                        break;
                    case 4:
                        $content = '取消申请';
                        break;
                    case 5:
                        $content = '已关闭';
                        break;
                }
            }
            $paln_list[$key]['title'] = $title;
            $paln_list[$key]['content'] = $content;
            $paln_list[$key]['add_date'] = local_date('Y-m-d H:i', $value['add_time']);
            $paln_list[$key]['add_time'] = localtotime( $value['add_time']);
        }
        return $paln_list;
    }

    /**
     * 处理进度状态 1：提交申请，2：客服受理，3：已完成
     * Created By caicm
     * @param int $status
     * @return int
     */
    public function get_workorder_status($status=0){
        //处理进度状态 1：提交申请，2：客服受理，3：已完成
        switch ($status){
            case 1:
                $workorder_status = 1;
                break;
            case 2:
                $workorder_status = 2;
                break;
            case 3:
                $workorder_status = 2;
                break;
            case 4:
                $workorder_status = 3;
                break;
            case 5:
                $workorder_status = 3;
                break;
        }
        return $workorder_status;
    }

    /*
     * 获取订单工单状态
     * Created By caicm
     * @param $in_overtime 超过售后期限
     * @param $in_time 在售后期限
     * @param $in_workorder 已申请售后
     * @return int (0、全部过期,1、可申请,2、部分申请,3、全部申请)
     */
    protected function get_order_workorder_type($in_workorder=0, $in_time=0, $in_overtime=0){
        //可申请
        $order_workorder_type = 1;
        //全部过期
        if($in_workorder==0 && $in_time==0 && $in_overtime==1){
            $order_workorder_type = 0;
        }
        //全部申请
        if($in_workorder==1 && $in_time==0 && $in_overtime==0){
            $order_workorder_type = 3;
        }
        //全部申请
        if($in_workorder==1 && $in_time==1 && $in_overtime==0){
            $order_workorder_type = 2;
        }

        return $order_workorder_type;

    }

    /*
     * 获取分类售后期限
     * Created By caicm
     * @param int $cat_id 商品分类id
     * @param int $confirm_time 订单确认时间
     * @return mixed
     */
    protected function get_category_deadline($cat_id, $confirm_time){

        //获取1级分类id
        $parent_cat_id = D('Category')->findLevelCatId($cat_id, 1);

        //是否在生鲜类
        if(in_array($parent_cat_id, $this->fresh_cat)){
            //售后期限
            $deadline = $confirm_time + $this->fresh_time;
        }else{
            //售后期限
            $deadline = $confirm_time + $this->other_time;
        }

        //是否在售后期限 1：是 ， 0：否
        $is_deadline = $deadline > gmtime() ? 1 : 0;

        return $is_deadline;

    }

    //获取售后处理原因处理方式
    public function get_cause(){

        $dispose_way =array(
            array(
                'dispose_id' => 1,
                'dispose_title' => '退款'
            )
        );

        $cause_list = array(
            array(
                'cause_id' => 1,
                'cause_title' => '生鲜类质量问题',
                'is_remark' => 1,
                'dispose_way' => $dispose_way
            ),
            array(
                'cause_id' => 7,
                'cause_title' => '非生鲜类质量问题',
                'is_remark' => 1,
                'dispose_way' => $dispose_way
            ),
            array(
                'cause_id' => 8,
                'cause_title' => '运输过程破损',
                'is_remark' => 1,
                'dispose_way' => $dispose_way
            ),
            array(
                'cause_id' => 9,
                'cause_title' => '退款',
                'is_remark' => 1,
                'dispose_way' => $dispose_way
            ),
            array(
                'cause_id' => 10,
                'cause_title' => '产品不足称',
                'is_remark' => 1,
                'dispose_way' => $dispose_way
            ),
            array(
                'cause_id' => 2,
                'cause_title' => '商品临期',
                'is_remark' => 1,
                'dispose_way' => $dispose_way
            ),
            array(
                'cause_id' => 3,
                'cause_title' => '漏送',
                'is_remark' => 1,
                'dispose_way' => $dispose_way
            ),
            array(
                'cause_id' => 4,
                'cause_title' => '送错产品',
                'is_remark' => 1,
                'dispose_way' => $dispose_way
            ),
            array(
                'cause_id' => 5,
                'cause_title' => '投诉',
                'is_remark' => 1,
                'dispose_way' => array()
            ),
            array(
                'cause_id' => 6,
                'cause_title' => '其他服务',
                'is_remark' => 1,
                'dispose_way' => $dispose_way
            )
        );

        return $cause_list;

    }

    //获取售后处理说明
    public function get_remark(){
        $remark = array(
            '*混合支付金额将退回账户余额中。',
            '默认处理方式为退款，如需其他帮助请在微信公众号联系客服。',
            '红包一经使用不予退回，如有疑问请联系客服。',
            '商品质量问题请附上损坏图片，无图片被拒程度较高。',
            '一份商品内若有部分商品出现质量问题，需拍下全部商品数量及损坏商品数量图片。方便客服操作退款。'
        );
        return $remark;
    }

    /**
     * @param int $status
     * @return string
     */
    public function get_paln_text($status=1){
        switch ($status){
            case 1:
                $content = '您的申请已提交成功，待客服审核中';
                break;
            case 2:
                $content = '客服已审核';
                break;
            case 3:
                $content = '您的申请被拒绝';
                break;
            case 4:
                $content = '您的申请已取消';
                break;
            case 5:
                $content = '已关闭';
                break;
        }
        return $content;
    }


}